#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

void test0(){
    int * p = (int*)malloc(sizeof(int));
    *p = 100;
    free(p);
    p = nullptr;//安全回收

    //4代表将堆上的int型变量初始化为4
    int * p1 = new int(4);
    cout << *p1 << endl;
    delete p1;
    /* free(p1); */
    p1 = nullptr;

    //()中没有值代表将堆上的变量初始化为该类型的默认值
    int * p2 = new int();
    cout << *p2 << endl;
    delete p2;
    p2 = nullptr;

    char * ps = new char('a');
    cout << *ps << endl;
    delete ps;
    ps = nullptr;


    //不推荐这样写，没有小括号，无法在所有的平台上确保初始化
    /* int * p3 = new int; */
    /* cout << *p3 << endl; */
    
}

void test1(){
    //开辟数组空间，其中每个元素被初始化为相应类型的默认值
    int * p = new int[10]();
    cout << p << endl;

    for(int i = 0; i < 10; ++i){
        p[i] = i;
    }
    for(int i = 0; i < 10; ++i){
        cout << p[i] << " ";
    }
    cout << endl;
    delete [] p;
    p = nullptr;

    //1,0,0,0,0
    int * p2 = new int[5]{1};
    for(int i = 0; i < 5; ++i){
        cout << p2[i] << " ";
    }
    cout << endl;
    delete [] p2;
    p2 = nullptr;
}

void test2(){
    //在C++中使用C风格字符串的方式
    const char * p1 = "hello";
    /* p1[0] = 'H'; */


    cout << sizeof(p1) << endl;
    cout << strlen(p1) << endl;

    char * ps = new char[strlen(p1) + 1]();
    strcpy(ps,p1);

    //输出流运算符对char*有默认重载效果
    //会自动访问指针保存的地址上的内容
    //这里输出的不是地址值，而是字符串的内容
    cout << ps << endl;
    delete [] ps;
    ps = nullptr;

    /* for(int i = 0; i < 6; ++i){ */
    /*     cout << ps[i]; */
    /* } */
    /* cout << endl; */


    //error，大括号中的数据应该是char类型
    /* char * pstr = new char[6]{"hello"}; */
    char * pstr = new char[6]{'h','e','l','l','o'};
    for(int i = 0; i < 6; ++i){
        cout << pstr[i] << " ";
    }
    cout << endl;
    delete [] pstr;
    pstr = nullptr;
}


int main(void){
    test0();
    return 0;
}
